const fs = require('fs')
const path = require('path')
const express = require('express')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-renderer')

const app = express()

const serve = (path, cache) => express.static(resolve(path), {
  maxAge: cache && 1000 * 60 * 60 * 24 * 30
})

// 设置静态资源
app.use('/dist', serve('./dist', true))

function createRenderer (bundle, options) {
  return createBundleRenderer(bundle, Object.assign(options, {
    basedir: resolve('./dist'),
    runInNewContext: false
  }))
}

// 引入模板文件,fs.readFileSync读取文件内容
const templatePath = resolve('./src/index.template.html')
const template = fs.readFileSync(templatePath, 'utf-8')

// 这里只需要引入json文件，因为VueSSRServerPlugin会帮我们做映射
const bundle = require('./dist/vue-ssr-server-bundle.json')
const clientManifest = require('./dist/vue-ssr-client-manifest.json')

// 官方用法，可把clien和server文件传入，vue-ssr-server会自动做处理
const renderer = createRenderer(bundle, {
  template,
  clientManifest
})

function render (req, res) {
  const context = {
    title: 'ssr demo', // default title
    url: req.url
  }
  renderer.renderToString(context, (err, html) => {
    if (err) {
      // res.send(err)
      console.log(err)
    }
    res.send(html)
  })
}

app.get('*',  render)

// 端口监听
const port = process.env.PORT || 8080
app.listen(port, () => {
  console.log(`server started at localhost:${port}`)
})
